<script lang="ts" setup>
import TableAction from '#/components/TableAction/index.vue'
import { LocaleDictionaryPrefix } from '#/config'
import { treeMap } from '#/helper/treeHelper'
import { usePageCURD } from '#/hooks/usePageCURD'
import { usePagePermission } from '#/hooks/usePermission'
import { copyText } from '#/utils/copyTextToClipboard'
import { rebuildZStructure, toLocalesTreeOptions } from '#/utils/localesConfig'
import { Page } from '@vben/common-ui'
import { $t } from '@vben/locales'
import { useAsyncState } from '@vueuse/core'
import { Button, InputSearch, Spin, Tree } from 'ant-design-vue'
import { computed, nextTick, ref, watch } from 'vue'
import SubPageContent from '../dictionarySub/components/PageContent.vue'
import AddEditModal from './components/AddEditModal.vue'
import type { TableListItem } from './use/api'
import { PageApi } from './use/api'
import { PAGE_AUTH_CODE_PREFIX } from './use/config'
import { usePageList } from './use/usePageList'

const { pageList, formValues, getPageList: getPageListOrgin } = usePageList()
const { isLoading, execute: getPageList } = useAsyncState(getPageListOrgin, null)

const subPageContentRef = ref<InstanceType<typeof SubPageContent>>()

// 新增、编辑、删除
const {
    FormModal,
    add: handleCreate,
    edit: handleEdit,
    del: handleDelete,
    viewDetail: handleViewDetail
} = usePageCURD<TableListItem>({
    modalOptions: {
        connectedComponent: AddEditModal
    },
    delApi: PageApi.delete,
    onSuccess: () => {
        getPageList()
    }
})

// 权限判断
const { getPagePermissionKey, hasPagePermission } = usePagePermission(PAGE_AUTH_CODE_PREFIX)
const currentItem = ref<TableListItem>()

const expandedKeys = ref<string[]>([])

const pageListTree = computed(() => {
    const json = rebuildZStructure(
        (pageList.value || []).map((v) => {
            return {
                label: v.name,
                value: v.code
            }
        })
    )

    const prefix = (LocaleDictionaryPrefix || '').replace('.', '')

    if (prefix && json[prefix]) {
        return treeMap(toLocalesTreeOptions(json[prefix]), {
            conversion(v: any) {
                return {
                    ...v,
                    value: LocaleDictionaryPrefix + v.value
                }
            }
        })
    }

    return toLocalesTreeOptions(
        rebuildZStructure(
            (pageList.value || []).map((v) => {
                return {
                    label: v.name,
                    value: v.code
                }
            })
        )
    )
})

const subPageQueryParams = computed(() => {
    return {
        dictId: currentItem.value?.id
    }
})

const isDevEnv = import.meta.env.MODE === 'development'

watch(subPageQueryParams, () => {
    if (subPageQueryParams.value.dictId) {
        nextTick(() => {
            subPageContentRef.value?.GridApi?.formApi?.resetForm()
            subPageContentRef.value?.reload()
        })
    }
})

watch(pageList, (val) => {
    if (!currentItem.value && val?.length) {
        currentItem.value = val[0]
    }
})

function onClickItem(item: TableListItem) {
    currentItem.value = item
}

/**
 *  某数据操作
 * @param record
 */
function getActions(record: TableListItem) {
    const arr: any[] = [
        {
            label: $t('common.view'),
            tooltip: $t('common.view'),
            onClick: () => {
                handleViewDetail(record)
            },
            auth: getPagePermissionKey('view')
        },
        {
            label: $t('common.edit'),
            tooltip: $t('common.edit'),
            onClick: () => {
                handleEdit(record)
            },
            auth: getPagePermissionKey('edit')
        },
        {
            label: $t('common.delete'),
            color: '#bb1b1b',
            tooltip: $t('common.delete'),
            popConfirm: {
                title: $t('common.confirmDelete'),
                placement: 'left',
                onConfirm: () => {
                    handleDelete(record)
                }
            },
            auth: getPagePermissionKey('delete')
        }
    ]

    return arr
}

function getItemByKey(key: string) {
    return (pageList.value || []).find((v) => v.code === key)
}

function getActionsByKey(key: string) {
    const item = getItemByKey(key)
    if (!item) return []
    return getActions(item)
}

function onClickItemByKey(key: string) {
    const item = getItemByKey(key)

    if (!item) {
        toggleExpand(key)
        return
    }
    return onClickItem(item)
}

function toggleExpand(key: string) {
    if (expandedKeys.value.includes(key)) {
        expandedKeys.value = expandedKeys.value.filter((v) => v !== key)
    } else {
        expandedKeys.value.push(key)
    }
}

function copyTextCode(val: string) {
    copyText(val.replace(new RegExp(`^${LocaleDictionaryPrefix}`), ''))
}
</script>

<template>
    <Page auto-content-height>
        <div class="flex h-full bg-white p-8">
            <div class="flex flex-col border-r pr-5">
                <div>
                    <div class="flex w-full justify-center">
                        <Button
                            v-if="hasPagePermission('add')"
                            @click="handleCreate"
                            class="w-full"
                        >
                            {{ $t('common.create') }}
                        </Button>
                    </div>
                    <div class="mt-4 flex w-full justify-center">
                        <InputSearch
                            v-model:value="formValues.name"
                            :placeholder="$t('common.search')"
                            class="w-full"
                        />
                    </div>
                </div>

                <div class="mt-4 w-full flex-1 overflow-auto border-t pt-4" style="height: 0">
                    <Spin class="w-full" :tip="`${$t('common.loading')}...`" :spinning="isLoading">
                        <Tree
                            style="width: 400px"
                            v-model:expanded-keys="expandedKeys"
                            :tree-data="pageListTree"
                            :field-names="{ title: 'label', key: 'value' }"
                            block-node
                            show-line
                        >
                            <template #title="{ label, value }">
                                <div class="flex w-full items-center p-2 pr-0 hover:cursor-pointer">
                                    <div
                                        class="flex-1 truncate"
                                        style="width: 0"
                                        @click="onClickItemByKey(value)"
                                    >
                                        <div
                                            class="overflow-hidden text-ellipsis font-bold"
                                            :title="label"
                                        >
                                            {{ label }}
                                        </div>

                                        <div
                                            v-if="isDevEnv"
                                            class="overflow-hidden text-ellipsis text-xs text-gray-400"
                                            @click.stop="copyTextCode(value)"
                                        >
                                            ( {{ value }})
                                        </div>
                                    </div>

                                    <div>
                                        <TableAction :drop-down-actions="getActionsByKey(value)" />
                                    </div>
                                </div>
                            </template>
                        </Tree>
                    </Spin>
                </div>
            </div>
            <div class="flex w-full flex-col pl-5">
                <div class="flex-1 overflow-auto">
                    <SubPageContent
                        v-if="currentItem?.id"
                        ref="subPageContentRef"
                        :query-params="subPageQueryParams"
                    />
                </div>
            </div>
        </div>
        <FormModal @success="getPageList" />
    </Page>
</template>
